<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="游戏名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入游戏名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入版本"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:game:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:game:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:game:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:game:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="gameList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="游戏id" align="center" prop="gameId" />
      <el-table-column label="缩略图" align="center" width="120">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px; display: block;"
              :src="getThumbnailUrl(scope.row.imageUrl)"
              :preview-src-list="scope.row.imageUrl ? [getFullImageUrl(scope.row.imageUrl)] : []"
              fit="cover"
              :z-index="3000"
              :initial-index="0"
              append-to-body
              preview-teleported
              hide-on-click-modal
              loading="lazy"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="游戏名称" align="center" prop="name" />
      <el-table-column label="版本" align="center" prop="version" />
      <el-table-column prop="gameType" label="游戏类型" width="200">
        <template #default="scope">
          <dict-tag :options="sys_game_type" :value="scope.row.gameType" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:game:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:game:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改游戏管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="gameRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="游戏名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入游戏名称" />
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model="form.version" placeholder="请输入版本" />
        </el-form-item>
        <el-form-item label="游戏类型" prop="gameType">
          <el-radio-group v-model="form.gameType">
            <el-radio
                v-for="dict in sys_game_type"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="游戏图片">
<!--          <el-upload
              class="avatar-uploader"
              action="/dev-api/system/game/uploadImage"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              accept=".jpg,.png"
          >
            <img v-if="true" :src="form.imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>-->
          <el-upload
              class="avatar-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              accept=".jpg,.png"
          >
            <img v-if="form.imageUrl" :src="displayImageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<!--action="/dev-api/system/game/uploadImage"-->
<script setup name="Game">
import { listGame, getGame, delGame, addGame, updateGame } from "@/api/system/game"
import { Picture } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()
const { sys_game_type } = proxy.useDict("sys_game_type")

const gameList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 新增数据项
const uploadAction = ref(import.meta.env.VITE_APP_BASE_API + '/system/game/uploadImage');
const uploadHeaders = ref({
  Authorization: `Bearer ${localStorage.getItem('token')}`
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    version: null,
    imageUrl: ""
  },
  rules: {
  },
})

const { queryParams, form, rules } = toRefs(data)

// 计算属性：显示图片的完整URL
const displayImageUrl = computed(() => {
  if (!form.value.imageUrl) return '';
  return form.value.imageUrl.startsWith('http')
      ? form.value.imageUrl
      : import.meta.env.VITE_APP_BASE_API + form.value.imageUrl;
});


/** 查询游戏管理列表 */
function getList() {
  loading.value = true
  listGame(queryParams.value).then(response => {
    gameList.value = response.rows
    console.log(gameList)
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    gameId: null,
    name: null,
    version: null,
    imageUrl: ""
  }
  proxy.resetForm("gameRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.gameId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加游戏管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _gameId = row.gameId || ids.value
  getGame(_gameId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改游戏管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["gameRef"].validate(valid => {
    if (valid) {
      if (form.value.gameId != null) {
        updateGame(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGame(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _gameIds = row.gameId || ids.value
  proxy.$modal.confirm('是否确认删除游戏管理编号为"' + _gameIds + '"的数据项？').then(function() {
    return delGame(_gameIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/game/export', {
    ...queryParams.value
  }, `game_${new Date().getTime()}.xlsx`)
}

// 文件上传前处理
const beforeUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 上传成功处理（简化版）
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    form.value.imageUrl = res.url; // 直接使用后端返回的相对路径
    ElMessage.success('上传成功');
  } else {
    ElMessage.error('上传失败：' + res.msg);
  }
};
// 获取完整图片URL（用于预览大图）
const getFullImageUrl = (url) => {
  if (!url) return '';
  // 已经是完整URL则直接返回
  if (url.startsWith('http')) return url;
  // 拼接基础路径
  return import.meta.env.VITE_APP_BASE_API + url;
};

// 获取缩略图URL（纯前端缩放）
const getThumbnailUrl = (url) => {
  const fullUrl = getFullImageUrl(url);
  if (!fullUrl) return '';

  // 方案1：使用CSS缩放（简单但加载原图）
  return fullUrl;

  // 方案2：使用图片服务（需替换为实际服务地址）
  // return `https://images.weserv.nl/?url=${encodeURIComponent(fullUrl)}&w=100&h=100&fit=cover`;
};
/*function handleUploadSuccess(res) {
  if (res.code === 200) {
    //form.imageUrl = `${import.meta.env.BASE_URL}` + import.meta.env.VITE_APP_BASE_API + res.url;
    // 使用 axios 携带 Token 获取图片
    const fetchImage = async (url) => {
      const res = await axios.get(url, {
        responseType: 'blob',
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      });
      return URL.createObjectURL(res.data); // 生成临时访问链接
    };

// 使用示例
    const a = fetchImage(import.meta.env.VITE_APP_BASE_API + res.url);
    console.log(a)
  } else {
    ElMessage.error("上传失败：" + res.msg);
  }
}*/

getList()
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/* 方案1：纯CSS缩略图（不改变实际图片尺寸） */
.el-image__inner {
  object-fit: cover;
  width: 100px;
  height: 100px;
}

/* 错误状态样式 */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100px;
  height: 100px;
  background: #f5f7fa;
  color: #909399;
  border: 1px dashed #ddd;
}
.image-slot .el-icon {
  font-size: 30px;
}
</style>